package com.tianshi.yingxue.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.aliyun.oss.OSS;
import com.tianshi.yingxue.dao.VideoMapper;
import com.tianshi.yingxue.entity.Video;
import com.tianshi.yingxue.service.VideoService;
import com.tianshi.yingxue.utils.AliyunOssUtils;
import com.tianshi.yingxue.utils.FileUploadConstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.net.URL;
import java.util.Date;
import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Override
    public List<Video> queryAll() {
        // 使用Example可以添加查询条件
        Example example = new Example(Video.class);
        // 可以添加排序
        example.orderBy("createTime").desc();
        return videoMapper.selectByExample(example);
    }

    @Override
    public void add(Video video) {
        video.setStatus(1); // 默认状态为正常
        video.setCreateTime(new Date());
        videoMapper.insertSelective(video);
    }

    @Override
    @Transactional
    public void updateVideo(Video video) {
        // 1. 检查视频是否存在
        Video existingVideo = videoMapper.selectByPrimaryKey(video.getId());
        if (existingVideo == null) {
            throw new RuntimeException("视频不存在，ID: " + video.getId());
        }

        // 2. 执行更新操作
        int result = videoMapper.updateByPrimaryKeySelective(video);
        if (result == 0) {
            throw new RuntimeException("更新失败");
        }
    }
    @Override
    public void deleteOssFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        try {
            // 从URL中提取对象名
            String objectName = extractObjectName(filePath);

            // 检查文件是否存在
            boolean exists = ossClient.doesObjectExist(bucketName, objectName);
            if (!exists) {
                throw new RuntimeException("文件不存在: " + objectName);
            }

            // 执行删除
            ossClient.deleteObject(bucketName, objectName);

        } catch (Exception e) {
            throw new RuntimeException("删除文件失败: " + e.getMessage());
        }
    }

    private String extractObjectName(String filePath) {
        if (filePath.contains("://")) {
            try {
                URL url = new URL(filePath);
                String path = url.getPath();
                return path.startsWith("/") ? path.substring(1) : path;
            } catch (Exception e) {
                return filePath.substring(filePath.lastIndexOf("/") + 1);
            }
        }
        return filePath;
    }
    public boolean delete(Integer id) {
        // 先查询视频信息，用于删除OSS上的文件
        Video video = videoMapper.selectByPrimaryKey(id);
        if (video != null) {
            // 删除视频文件
            if (video.getVideoPath() != null && !video.getVideoPath().isEmpty()) {
                String videoObjName = getObjNameFromUrl(video.getVideoPath());
                AliyunOssUtils.deleteFile(FileUploadConstance.BUCKET, videoObjName);
            }

            // 删除封面文件
            if (video.getCoverPath() != null && !video.getCoverPath().isEmpty()) {
                String coverObjName = getObjNameFromUrl(video.getCoverPath());
                AliyunOssUtils.deleteFile(FileUploadConstance.BUCKET, coverObjName);
            }

            // 删除数据库记录
            return videoMapper.deleteByPrimaryKey(id) > 0;
        }
        return false;
    }

    private String getObjNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        // 如果URL包含域名，提取路径部分
        if (url.contains("://")) {
            try {
                URL uri = new URL(url);
                String path = uri.getPath();
                // 去除开头的斜杠
                return path.startsWith("/") ? path.substring(1) : path;
            } catch (Exception e) {
                // 如果解析失败，尝试直接提取文件名
                return url.substring(url.lastIndexOf("/") + 1);
            }
        }

        // 如果已经是相对路径，直接返回
        return url;
    }

    @Override
    public void changeStatus(Integer id, Integer status) {
        Video video = new Video();
        video.setId(id);
        video.setStatus(status);
        videoMapper.updateByPrimaryKeySelective(video);
    }
    @Override
    public Video queryById(Integer id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的视频ID");
        }
        return videoMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void updateStatus(Integer id, Integer status) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的视频ID");
        }
        if (status == null || (status != 0 && status != 1)) {
            throw new IllegalArgumentException("状态值必须是0或1");
        }

        Video video = new Video();
        video.setId(id);
        video.setStatus(status);
        videoMapper.updateByPrimaryKeySelective(video);
    }

    @Override
    public List<Video> searchVideo(String content) {
        if (StringUtils.isBlank(content)) {
            throw new IllegalArgumentException("搜索内容不能为空");
        }

        Example example = new Example(Video.class);
        Example.Criteria criteria = example.createCriteria();

        // 多字段模糊查询
        criteria.orLike("title", "%" + content + "%")
                .orLike("description", "%" + content + "%");

        // 只查询正常状态的视频
        criteria.andEqualTo("status", 1);

        return videoMapper.selectByExample(example);
    }
}
